package cn.wizzer.app.web.commons.ext.websocket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;

public class MyWebSocketClient extends WebSocketClient{

    public MyWebSocketClient(String url) throws URISyntaxException {
        super(new URI(url));
    }

    @Override
    public void onOpen(ServerHandshake shake) {
        System.out.println("握手...");
        for(Iterator<String> it=shake.iterateHttpFields();it.hasNext();) {
            String key = it.next();
            System.out.println(key+":"+shake.getFieldValue(key));
        }
    }

    @Override
    public void onMessage(String paramString) {
        System.out.println("接收到消息："+paramString);
    }

    @Override
    public void onClose(int paramInt, String paramString, boolean paramBoolean) {
        System.out.println("关闭...");
    }

    @Override
    public void onError(Exception e) {
        System.out.println("异常"+e);

    }

    public void waitForConnected(){
        boolean flag = true;
        while (flag) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(this.getReadyState().equals(READYSTATE.OPEN)){
                flag = false;
            }
        }
    }

    public void syncConnect(){
        super.connect();
        this.waitForConnected();
    }

    public static void main(String[] args) {
        try {
            MyWebSocketClient client = new MyWebSocketClient("ws://127.0.0.1:8090/ws");
            client.connect();
            while (!client.getReadyState().equals(READYSTATE.OPEN)) {
                System.out.println("还没有打开");
            }
            System.out.println("建立websocket连接");
            client.send("/attendant/open?" +
                    "content=decodeURIParam" +
                    "&type=TEXT" +
                    "&appid=b29d8c15ecf64df0b96714e213e0e2e7" +
                    "&token=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJiMjlkOGMxNWVjZjY0ZGYwYjk2NzE0ZTIxM2UwZTJlNyIsImV4cCI6MTU5MzY4MDUxN30.Oogsdrq3c-F-PCy6uolibKVI3lyjU0dKYWWVDhogTUKqt5EYpdaz86d7q8-gLiqkYPNZS2bCBg8W9fbIJ4v-wQ");
            client.close();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

}